Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
React Hook "React.useState" cannot be called inside a callback. React Hooks must be called in a React function component

I am trying to make a default state based on user context but I couldn't get to use context outside tha callback of <myContext.Consumer>{myContext => {}}</myContext.Consumer>. I get the above error when I try to use setState in the callback

Here is my use case:

import * as React from 'react'
import Box from '@mui/material/Box'
import PageTitle from '../01_shared/PageTitle'

import { appCtx } from '../01_shared/appContext'

const MyComponent = () => {

  const [options, setOptions] = React.useState({
    currency: userContext.currency, // <=I need user context information here
  })

  return <appCtx.Consumer>{translationContext => {
    // I cannot use React.useState here
    return (
      <Box>
        <PageTitle>Hello {userCtx.firstName} you have 3 {options.currency}</PageTitle>
      </Box>
    )
  }}</appCtx.Consumer>
};

export default MyComponent

I know I can set the state straight after having access to the userContext but that seem more like a workaround than a proper solution.

Could you point me to the right direction please ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Function components can use the useContext hook to get context values, and thus you don't need to render an <appCtx.Consumer>:

const MyComponent = () => {
  const userContext = React.useContext(appCtx);
  const [options, setOptions] = React.useState({
    currency: userContext.currency,
  });

  return (
    <Box>
      <PageTitle>
        Hello {userContext.firstName} you have 3 {options.currency}
      </PageTitle>
    </Box>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda